package com.sto.stoapp.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.StoConfig;
import com.sto.stoapp.activity.administrator.StoAdminMainActivity;
import com.sto.stoapp.activity.administrator.system.SystemKeyMgrActivity;
import com.sto.stoapp.activity.aviation.StoAviationSelectActivity;
import com.sto.stoapp.activity.center.StoCenterSelectActivity;
import com.sto.stoapp.activity.sales.StoSalesMainActivity;
import com.sto.stoapp.activity.sales.StoSitePointSelectActivity;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.ErrorRecordManager;
import com.sto.stoapp.db.manager.SiteFullManager;
import com.sto.stoapp.db.manager.UserInfoManager;
import com.sto.stoapp.db.manager.UserManager;
import com.sto.stoapp.file.SmzFile;
import com.sto.stoapp.http.BaseMessage;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.request.LoginRequest;
import com.sto.stoapp.http.response.LoginResponse;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.AccessControlManager;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.manager.DownApk;
import com.sto.stoapp.manager.DownApk.ExceptionClickListener;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.md5.Md5;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.thread.BarInfoUploadThread;
import com.sto.stoapp.thread.BillControlsThread;
import com.sto.stoapp.thread.BillFilterThread;
import com.sto.stoapp.thread.DeleteSdFileThread;
import com.sto.stoapp.thread.GetPayMentOnOffThread;
import com.sto.stoapp.thread.LoginThread;
import com.sto.stoapp.thread.SystemSettingSynchThread;
import com.sto.stoapp.thread.VerificationUpgradeThread;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.util.DateUtil;
import com.sto.stoapp.util.FileUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.JPushUtil;
import com.sto.stoapp.util.StringUtil;
import com.sto.stoapp.util.TraceUtil;
import com.sto.stoapp.util.UnInstallUtil;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;

import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import sto.android.app.StoTongJNI;


//import com.kaicom.stoapp.db.manager.LoginInfoManager;

public class StoLoginActivity extends Activity {

    /*
     * @修改内容：需要显示机器唯一码
     *
     * @修改人：mgf
     */
    // IMEI号和网点编号
    private TextView imeiText, siteCodeText, barNumber;
    // 工号、密码
    private StoHhmEditText jobNumberEdit, pwdNumberEdit;

    // 设置、登陆
    private Button settingsBtn, loginBtn;
    // 定时清空登陆信息的广播
    private LoginBroad loginBroad;
    // imei设置
    private final int IMIE_SET_RESULT = 0xfd;

    // mgf：UI调整
    private TextView versionCode, machineCode;

    private String jobId = "";

    //Add by wangjie 极光注册标志
    private static final int MSG_SET_TAGS = 1002;
    //End by wangjie

    @SuppressWarnings("static-access")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        InitScanTime();
        setContentView(R.layout.sto_login);
        loginBroad = new LoginBroad();
        registerReceiver(loginBroad, new IntentFilter(LoginBroad.LOGIN_ACTION));
        initWidget();
        initListener();
        SoundManager.getInstance(this);
        ExceptionLog.getInstance().init();
        StoApplication.getStoJni().TurnOffStatusBarExpand();
        if (StoApplication.getStoJni().GetStatusScreenLock() == 1) {
            StoApplication.getStoJni().TurnOffScreenLock();
        }
        CheckImie();

        StoFilePreference.getInstance(this).setBootStrap(true);

        SystemKeyMgrActivity.light(this, StoFilePreference.getInstance(this)
                .getLightSwitch());
        SystemKeyMgrActivity.sound(this, StoFilePreference.getInstance(this)
                .getPromptSound());

        if (StoFilePreference.getInstance(this).getAutoUploadTime() < 5) {
            StoFilePreference.getInstance(this).setAutoUploadTime(10);
        }
        AlarmClockManager.getInstance(this).closeUploadAlarm();
        ErrorRecordManager.getInstance(this).deleteOldData();
        checkTime();
        new DeleteSdFileThread(this).run();
//        if ( StoApplication.getStoJni().GetStatusTouch_Home_screen() == 1)
//            StoApplication.getStoJni().Disable_home_touch_screen();
    }

    private void checkTime() {
        long time = new Date().getTime()
                - StoFilePreference.getInstance(this).getPowerOffTime();
        if (time < 0)
            StoApplication.getStoJni().SetSystemTime(
                    "" + StoFilePreference.getInstance(this).getPowerOffTime());
        else if (time > 24 * 60 * 60 * 1000l * 30)
            StoFilePreference.getInstance(this).setNeedLogin(true);
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == LoginThread.LOGIN_REQUEST_CODE) {
                //这里是登录成功的处理
                loginResponseEvent((LoginResponse) msg.obj, false, true);
            } else if (msg.what == VerificationUpgradeThread.FORCIBLE_UPGRADE) {
                showForcibleUpgradeDialog((LoginResponse) msg.obj);
            } else if (msg.what == VerificationUpgradeThread.SELECTABLE_UPGRADE) {
                showSelectableUpgradeDialog((LoginResponse) msg.obj);
            } else if (msg.what == VerificationUpgradeThread.NO_UPGRADE) {
                LoginRequest request = new LoginRequest(StoLoginActivity.this,
                        jobId, pwdNumberEdit.getText().toString(),
                        TraceUtil.getTraceTimes()); // <=

                //这里才是真正的登录，点击登录是先调用是否需要更新的接口，不需要更新再调登录
                LoginThread loginThread = new LoginThread(
                        StoLoginActivity.this, request, handler);
                loginThread.start();
            } else if (msg.what == VerificationUpgradeThread.UPGRADE_ERROR) {
                LoginResponse response = (LoginResponse) msg.obj;
                if (response == null) {
                    Helper.showSoundToast(StoLoginActivity.this,
                            getText(R.string.request_failure).toString(), false);
                    OfflineMode(jobId, pwdNumberEdit.getText().toString());
                } else {
                    Helper.showLongToast(StoLoginActivity.this,
                            response.resMessage);
                    Helper.showSoundToast(StoLoginActivity.this,
                            getText(R.string.login_failure).toString(), false);
                }
            }
            //Add by wangjie 设置Jpush别名
            else if(msg.what==MSG_SET_TAGS){
                Log.d("sto", "Set tags in handler.");
                JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
            }
            //End by wangjie 设置Jpush别名
        }
    };

    private void showForcibleUpgradeDialog(LoginResponse response) {

        BaseDialog dialog = new BaseDialog(this);
        dialog.setMessage("您使用的版本已过期，请升级版本！");
        dialog.show();
        dialog.getvCanncel().setVisibility(View.GONE);

        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {

                if (res) {
                    upgrade();
                }
            }
        });

    }

    private void showSelectableUpgradeDialog(LoginResponse response) {
        BaseDialog dialog = new BaseDialog(this);
        dialog.setMessage("检测到新版本，是否升级！\n新版本：" + response.newSoftVersion
                + "\n过期时间:" + response.updateDate);
        dialog.show();
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {

                if (res) {
                    upgrade();
                } else {
                    LoginRequest request = new LoginRequest(
                            StoLoginActivity.this, jobId, pwdNumberEdit
                            .getText().toString(), TraceUtil
                            .getTraceTimes()); // <=

                    LoginThread loginThread = new LoginThread(
                            StoLoginActivity.this, request, handler);
                    loginThread.start();
                }
            }
        });
        // dialog.show();
    }

    private void upgrade() {

        final DownApk downApk = new DownApk(this);
        downApk.startDown();
        downApk.setListener(new ExceptionClickListener() {

            @Override
            public void onExceptionClickListener(final String exception) {
                downApk.dismiss();
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Helper.showToast(StoLoginActivity.this, exception);
                    }
                });
            }
        });

    }
    private void CheckImie() {

        String imie = StoApplication.getStoJni().GetMachineCode();
        if (StringUtil.isEmpty(imie)) {
            Intent intent = new Intent(this, StoImieActivity.class);
            startActivityForResult(intent, IMIE_SET_RESULT);
        } else {
            StoFilePreference.getInstance(this).setMachineCode(
                    imie.trim());
            imeiText.setText (imie.trim());
        }

    }
    private void InitScanTime() {
        StoConfig.NO_VOID = true;
        StoApplication.getStoJni().SetScannerTimerOut(10);
//		int s = StoFilePreference.getInstance(this).getScanHeaderTime();
//		if (StoApplication.getStoJni().GetScannerModel() != StoJNI.MODEL_SE955
//				&& s > 10) {
//			jni.SetScannerTimerOut(10);
//			StoFilePreference.getInstance(this).setScanHeaderTime(10);
//		} else {
//			jni.SetScannerTimerOut(s);
//		}

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == IMIE_SET_RESULT && resultCode == RESULT_OK) {
            String imie = StoApplication.getStoJni().GetMachineCode();
            if (imie == null) {
                return;
            }
            StoFilePreference.getInstance(this).setMachineCode(imie.trim());
            imeiText.setText(imie.trim());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginBroad != null) {
            unregisterReceiver(loginBroad);
        }

        handler.removeMessages(LoginThread.LOGIN_REQUEST_CODE);
    }

    /**
     * 登陆成功
     * @param response
     * @param isOffline
     * @param isNetResponse
     *
     */
    private void loginResponseEvent(LoginResponse response, boolean isOffline,
                                    boolean isNetResponse) {
        String attributeBit = "";
        if (response == null) {
            Helper.showSoundToast(this, getText(R.string.request_failure)
                    .toString(), false);
            OfflineMode(jobId, pwdNumberEdit.getText().toString());
        } else {
            AccessControlManager.getInstance(this).initConfig();
            if (response.respCode.equals(BaseMessage.REQUEST_SUCCESS)) {
                // 系统功能同步
                new SystemSettingSynchThread(this, handler).start();

                // 硬件信息采集
                new BarInfoUploadThread(this, handler).start();
                StoFilePreference.getInstance(this).setNeedLogin(false);
                setTime(response.systemTime);
                StoFilePreference.getInstance(this).setSessionId(
                        response.sessionId);
                AccessControlManager.getInstance(this).ProgramRole(
                        response.orgType, response.getOrgAirType(),
                        response.role);

                //登录用户的角色
                attributeBit = AccessControlManager.getInstance(this)
                        .getProgramRole();

                //Add by wangjie登陆成功设置Jpush标签(网点)
                String siteCode=StoFilePreference.getInstance(this).getSiteCode();

                String[] sArray = new String[]{siteCode};
                //调用JPush API设置Tag
                Set<String> tagSet = new LinkedHashSet<String>();
                for (String sTagItme : sArray) {
                    tagSet.add(sTagItme);
                }
                handler.sendMessage(handler.obtainMessage(MSG_SET_TAGS, tagSet));

                //开启获取过滤订单的线程
                new BillFilterThread(siteCode,this).start();
                new BillControlsThread(siteCode,StoApplication.getAppInstance()).start();
                new GetPayMentOnOffThread(this).start();
                //End by wangjie登陆成功设置Jpush标签

                StoFilePreference.getInstance(this).setUserCode(jobId);
                StoFilePreference.getInstance(this).setPwdInfo(
                        pwdNumberEdit.getText().toString());
                StoFilePreference.getInstance(this).setSiteOrgType(
                        response.orgType);
                StoFilePreference.getInstance(this).setSiteOrgAirType(
                        response.orgAirType);
                String jobName = UserInfoManager.getInstance(this)
                        .getJobNameByCode(
                                StoFilePreference.getInstance(this)
                                        .getSiteCode(), jobId);
                if (TextUtils.isEmpty(jobName))
                    jobName = jobId;
                StoFilePreference.getInstance(this).setUserName(jobName);
                StoFilePreference.getInstance(this).setSiteName(
                        SiteFullManager.getInstance(this).querySiteCodeName(
                                StoFilePreference.getInstance(this)
                                        .getSiteCode()));
                if (isNetResponse) {
                    StoFilePreference.getInstance(this).setOnLineLoginTime(
                            new Date().getTime());
                }
                // LoginInfoEntity entity = new LoginInfoEntity();
                // entity.setJobNumber(jobId);
                // entity.setPwdInfo(pwdNumberEdit.getText().toString());
                // entity.orgType = response.orgType;
                // entity.orgAirType = response.getOrgAirType();
                // entity.setSiteName(StoFilePreference.getInstance(this)
                // .getSiteCode());
                // entity.setLoginAttribute(attributeBit);
                // LoginInfoManager.getInstance(this).insertOnly(entity);

                if (attributeBit.equals(BaseMessage.SALES_VERSION)) {

                    UnifiedStaticType.loginType = BaseMessage.SALES_VERSION;
                    allStartService();
                    // startDown();

                    intoMenu(StoSitePointSelectActivity.class, isOffline);

                }
                else if (attributeBit.equals(BaseMessage.SCANNER_VERSION)) {

                    UnifiedStaticType.loginType = BaseMessage.SCANNER_VERSION;
                    allStartService();
                    intoMenu(StoSitePointSelectActivity.class, isOffline);

                }
                else if (attributeBit.equals(BaseMessage.CENTER_VERSION)) {
                    // if (response.getAttributeBit().equals(
                    // BaseMessage.CENTER_VERSION)) {
                    // 开启服务
                    UnifiedStaticType.loginType = BaseMessage.CENTER_VERSION;
                    allStartService();

                    intoMenu(StoCenterSelectActivity.class, isOffline);
                }
                else if (attributeBit.equals(BaseMessage.AVIATION_A_VERSION)
                        || attributeBit.equals(BaseMessage.AVIATION_T_VERSION)) {

                    UnifiedStaticType.loginType = BaseMessage.AVIATION_T_VERSION;
                    allStartService();
                    // startAviationDown(false);
                    intoMenu(StoAviationSelectActivity.class, isOffline);

                } else if (("").equals(attributeBit)) {

                    Helper.showSoundToast(this, "请维护巴枪角色", false);
                    return;

                } else {
                    return;
                }

                finish();
            } else {
                Helper.showLongToast(this, response.resMessage);
                Helper.showSoundToast(this, getText(R.string.login_failure)
                        .toString(), false);

                // OfflineMode(jobId, pwdNumberEdit.getText().toString());
            }
        }
    }

    private void setTime(String systemTime) {
        if (!("").equals(systemTime)) {
            StoApplication.getStoJni().SetSystemTime(DateUtil.getLongTime(
                    DateUtil.DEFAULT_DATE_TIME_FORMAT, systemTime) + "");
        }

    }

    private void intoMenu(final Class<?> c, boolean isLocal) {
        // new SystemSettingSynchThread(this).start();
        // new BarInfoUploadThread(this).start();
        Intent intent = new Intent(this, c);
        intent.putExtra(BaseMessage.IS_LOCAL_LOGIN, isLocal);
        // intent.putStringArrayListExtra(BaseMessage.ROLE_MENU, roles);
        startActAndStartAlarm(intent);
    }

    // private boolean isBackKey = false;

    private void initListener() {
        settingsBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StoLoginActivity.this,
                        StoSettingsActivity.class);
                startActivity(intent);
            }
        });

        loginBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //Add by wj 点击登录的时候如果检测到旧包未卸载，禁止登录
                String pName=UnInstallUtil.getPackageName(StoLoginActivity.this);
                boolean isUnInstall=UnInstallUtil.checkPackage(StoLoginActivity.this,pName);
                if(isUnInstall){
                    UnInstallUtil.unInstallApp(StoLoginActivity.this,pName);
                    return;
                }
                //End by wj

                if (!StoConfig.needLogin) {
                    testLogin();
                    return;
                }
                loginEvent(jobId, pwdNumberEdit.getText().toString());

            }
        });

        jobNumberEdit.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {

            }

            @Override
            public void onEditClickListener(View v) {

                if (jobNumberEdit.getText().toString().length() > 0) {
                    pwdNumberEdit.requestFocus();
                    pwdNumberEdit.setSelection(pwdNumberEdit.getText()
                            .toString().length());
                } else {

                    //Modify by wangjie
                    if(!"".equals(pwdNumberEdit.getText().toString().trim()))
                        Helper.showSoundToast(StoLoginActivity.this, "工号不能为空!",
                                false);
                }
            }
        });

        jobNumberEdit
                .setOnFocusChangeListener(new View.OnFocusChangeListener() {

                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            jobNumberEdit.setText(jobId);
                            jobNumberEdit.setSelection(jobId.length());
                        } else {
                            showUserName(jobNumberEdit.getText().toString());
                        }
                    }
                });

        pwdNumberEdit.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                jobNumberEdit.requestFocus();
            }

            @Override
            public void onEditClickListener(View v) {

                loginEvent(jobId, pwdNumberEdit.getText().toString());

            }
        });

    }

    private void showUserName(String jobNumber) {

        if (jobNumber.equals(UnifiedStaticType.ADMIN_USER_INFO)
                || jobNumber.equals(UnifiedStaticType.EXIT_USER)) {
            jobNumberEdit.setText("管理员");
        } else {
            // String userName = LoginInfoManager.getInstance(this)
            // .queryUserNameByJob(jobNumber);
            // if (!TextUtils.isEmpty(userName)) {
            // jobNumberEdit.setText(userName);
            // // 保存用户id
            // }
        }
        jobId = jobNumber;
    }

    private void loginEvent(String jobNumber, String pwdInfo) {

        //Add by wj
        if("".equals(jobNumber) || "".equals(pwdInfo)){
            Toast.makeText(this,"账号或密码为空...",Toast.LENGTH_SHORT).show();
            return;
        }
        //End by wj

        if (jobNumber.equals("555555") && "159357".equals(pwdInfo)) {
            FileUtil.copyFile(
                    "/data/data/com.kaicom.stoapp.activity/databases/StoDatabase.db",
                    FileUtil.SDPATH + "sto/StoDatabase.db");
        }
        if (!checkExit(jobNumber, pwdInfo)) {
            // 判断是否为管理员账号
            if (jobNumber.equals(UnifiedStaticType.ADMIN_USER_INFO)) {

                if (pwdInfo.equals(UnifiedStaticType.ADMINISTRATOR_KEY1)
                        || pwdInfo.equals(UnifiedStaticType.SUPER_ADMINISTRATOR_KEY)
                        || pwdInfo.equals(UnifiedStaticType.KAICOM_KEY) || pwdInfo.equals(UnifiedStaticType.ADMINISTRATOR_KEY2)) {
                    if (pwdInfo.equals(UnifiedStaticType.SUPER_ADMINISTRATOR_KEY)) {
                        StoFilePreference.getInstance(this).setUserType(
                                UnifiedStaticType.SUPER_ADMINISTRATOR_KEY);
                        StoFilePreference.getInstance(this)
                                .setSuperAdministrator(true);
                    } else {
                        StoFilePreference.getInstance(this)
                                .setSuperAdministrator(false);
                        StoFilePreference.getInstance(this).setUserType("");
                    }
                    Intent intent = new Intent(this, StoAdminMainActivity.class);
                    intent.putExtra("type", true);
                    startActivity(intent);
                    StoFilePreference.getInstance(this).setUserCode("");
                    StoFilePreference.getInstance(this).setPwdInfo("");
                    finish();
                    return;
                }
            }
            if (!StoFilePreference.getInstance(this).getNeedLogin()) {
                StoFilePreference.getInstance(this).setNeedLogin(
                        needOnLineLogin());
            }

            if (!(StoFilePreference.getInstance(this).getNeedLogin())) {
                localCheckLogin(jobNumber, pwdInfo, false);
            } else {
                if (Helper.isNumeric(jobNumber)) {
                    if (checkNet()) {
                        LoginRequest request = new LoginRequest(
                                StoLoginActivity.this, jobId, pwdNumberEdit
                                .getText().toString(),
                                TraceUtil.getTraceTimes()); // <=

                        VerificationUpgradeThread upgradeThread = new VerificationUpgradeThread(
                                this, request, handler);
                        upgradeThread.start();
                    } else {
                        OfflineMode(jobNumber, pwdInfo);
                    }

                } else {
                    Helper.showSoundToast(this, getText(R.string.digit_error)
                            .toString(), false);
                }
            }

        }
    }

    private boolean needOnLineLogin() {
        return (new Date().getTime() - StoFilePreference.getInstance(this)
                .getOnLineLoginTime()) > 24 * 60 * 60 * 1000l;
    }

    private void localCheckLogin(String jobNumber, String pwdInfo,
                                 boolean isOffline) {
        LoginResponse response = new LoginResponse();
        List<String> roles = null;
        if (UserInfoManager.getInstance(this).hasThisUser(
                StoFilePreference.getInstance(this).getSiteCode(), jobId,
                Md5.getMD5Hex(pwdInfo))) {
            roles = UserManager.getInstance(this).queryRoleByPw(
                    StoFilePreference.getInstance(this).getSiteCode(), jobId);
            if (roles != null) {
                response.respCode = BaseMessage.REQUEST_SUCCESS;
                response.sessionId = "";
                response.systemTime = "";
                response.orgType = StoFilePreference.getInstance(this)
                        .getSiteOrgType();
                response.orgAirType = StoFilePreference.getInstance(this)
                        .getSiteOrgAirType();
                response.role = roles;

                loginResponseEvent(response, isOffline, false);
            } else {
                StoFilePreference.getInstance(this).setNeedLogin(true);
                loginEvent(jobId, pwdNumberEdit.getText().toString());
                Helper.showToast(this, "本地访问不到角色，直接在线登录");
                // Helper.showSoundToast(this, "请维护巴枪角色", false);
            }

        } else {
            Helper.showSoundToast(this, "工号不存在或密码错误", false);
        }
    }

    private boolean checkNet() {
        if (!Helper.isNetworkAvailable(this)) {
            Helper.showSoundToast(this, "网络不可用", false);
            return false;
        }

        return true;
    }

    private void OfflineMode(final String jobId, final String pwd) {
        if (!StoConfig.OffileMode)
            return;
        final BaseDialog dialog = new BaseDialog(this);
        dialog.setTitles(getString(R.string.offline_mode));
        dialog.show();
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
                if (res) {
                    localCheckLogin(jobId, pwd, true);
                }
            }
        });
    }

    private boolean checkExit(String jobNumber, String pwdInfo) {
        if (UnifiedStaticType.EXIT_USER.equals(jobNumber)
                && UnifiedStaticType.EXIT_USER_PWD.equals(pwdInfo)) {
            showExit();

            return true;
        } else {
            return false;
        }
    }

    private void initWidget() {
        imeiText = (TextView) findViewById(R.id.sto_imei);
        // TelephonyManager telephonyManager = (TelephonyManager) this
        // .getSystemService(Context.TELEPHONY_SERVICE);

        siteCodeText = (TextView) findViewById(R.id.net_site_code);
        barNumber = (TextView) findViewById(R.id.bar_code);
        jobNumberEdit = (StoHhmEditText) findViewById(R.id.sto_job_number);
        // jobNumberEdit
        // .setText(StoFilePreference.getInstance(this).getUserInfo());
        pwdNumberEdit = (StoHhmEditText) findViewById(R.id.sto_pwd_number);
        // pwdNumberEdit.setText(StoFilePreference.getInstance(this).getPwdInfo());
        // pwdNumberEdit.setInputType(InputType.TYPE_NULL);
        settingsBtn = (Button) findViewById(R.id.sto_settings);
        loginBtn = (Button) findViewById(R.id.sto_login);

        versionCode = (TextView) findViewById(R.id.version_code);
        machineCode = (TextView) findViewById(R.id.machine_code);
        pwdNumberEdit.setTransformationMethod(PasswordTransformationMethod
                .getInstance());
        pwdNumberEdit.postInvalidate();

        initTest();

    }

    // int times = 0;

    private void initTest() {
        RadioGroup group = (RadioGroup) findViewById(R.id.RadioGroup);
        group.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        siteCodeText.setText(StoFilePreference.getInstance(this).getSiteCode());
        String barCode = StoFilePreference.getInstance(this).getBarCodeNumber();
        int number = 0;
        try {
            number = Integer.parseInt(barCode);
        } catch (Exception e) {
        }
        if (number == 0) {
            barNumber.setText("");
        } else {
            barNumber.setText(barCode);
        }

        jobNumberEdit.requestFocus();

        EditText edit = new EditText(this);
        edit.setInputType(Configuration.KEYBOARD_QWERTY);
        String pdaBrand = StoTongJNI.getmPdaBrand();
        String factory = "";
        if (pdaBrand.equals("kaicom")) {
            System.out.println("####brand:Kaicom");
            factory = "凯立";
        } else if (pdaBrand.equals("urovo")) {
            System.out.println("####brand:Urovo");
            factory = "优博讯";
        } else if (pdaBrand.equals("rongxin")) {
            System.out.println("####brand:RongXin");
            factory = "荣信";
        } else if (pdaBrand.equals("wangfeng")) {
            System.out.println("####brand:WangFeng");
            factory = "网风";
        } else if(pdaBrand.equals("edb")){
            factory="e递宝";
        }else if(pdaBrand.equals("alps")){
            factory="智联天地";
        }
        else {
            factory = "凯立";
        }
        versionCode.setText(factory + Build.MODEL.trim() + " "
                + Helper.getVersionName(this));
        if (StoApplication.getStoJni().GetMachineCode() != null) {
            machineCode.setText(StoApplication.getStoJni().GetMachineCode()
                    .trim());
        }

    }

    class LoginBroad extends BroadcastReceiver {

        public static final String LOGIN_ACTION = "login_action";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(LOGIN_ACTION)) {
                // StoFilePreference.getInstance(context).clearLoginInfo();
                // 清空订单和时间同步状态
                // StoFilePreference.getInstance(context).clearOderAndTimeSynData();
                System.out.println("***LoginBroad***");
                Helper.loginOut(context);
            }
        }

    }
    private void allStartService() {
        // 开启上传数据表线程
        Intent serviceUpload = new Intent(this, UploadDataService.class);
        startService(serviceUpload);
        // 开启下载服务
        // startService(new Intent(this, StoDownServer.class));
        // 开启定时器服务
        Intent timingService = new Intent(this, TimingService.class);
        timingService.putExtra(UnifiedStaticType.TIMING_TYPE,
                UnifiedStaticType.AUTO_UPLOAD_TIMING);
        startService(timingService);
        new SmzFile(StoApplication.getAppInstance()).downSmzZjSiteCodeFile(false);
    }

    private void startSalesDown(boolean isOffline) {
        Intent downIntent = new Intent(this, StoDownServer.class);
        if (!isOffline) {
            downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{
                    MessageType.PROBLEM_TYPE, MessageType.OFFLINE_LOGIN,
                    MessageType.PROVINCE_TYPE, MessageType.NEXT_SITE_CODE,
                    MessageType.ORDER_REASON_TYPE, MessageType.SERVER_SMS_TYPE,
                    MessageType.BILLCODE_ISSUE, MessageType.OFFLINE_LOGIN});
        } else {
            downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{});
        }
        startService(downIntent);
    }

    private void startScanDown(boolean isOffline) {
        Intent downIntent = new Intent(this, StoDownServer.class);
        if (!isOffline) {
            downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{
                    MessageType.PROBLEM_TYPE, MessageType.OFFLINE_LOGIN,
                    MessageType.PROVINCE_TYPE, MessageType.NEXT_SITE_CODE,
                    MessageType.SITE_CODE_FULL, MessageType.SITE_SALEAS_TYPE,
                    MessageType.SERVER_SMS_TYPE, MessageType.BILLCODE_ISSUE,
                    MessageType.OFFLINE_LOGIN});
        } else {
            downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{});
        }
        startService(downIntent);
    }

    private void startCenterDown(boolean isOffline) {
        Intent downIntent = new Intent(this, StoDownServer.class);
        if (!isOffline) {
            downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{
                    MessageType.OFFLINE_LOGIN, MessageType.PROBLEM_TYPE,
                    MessageType.PROVINCE_TYPE, MessageType.NEXT_SITE_CODE,
                    MessageType.SITE_CODE_FULL, MessageType.SITE_SALEAS_TYPE});
        } else {
            downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{});
        }
        startService(downIntent);
    }

    /*
     * private void startAviationDown(boolean isOffline) { Intent downIntent =
	 * new Intent(this, StoDownServer.class); if (!isOffline) { //
	 * downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[] { //
	 * MessageType.SYNCH_TIME_TYPE, MessageType.OFFLINE_LOGIN, //
	 * MessageType.PROBLEM_TYPE, MessageType.PROVINCE_TYPE, //
	 * MessageType.NEXT_SITE_CODE, MessageType.SITE_CODE_FULL, //
	 * MessageType.SITE_SALEAS_TYPE, // MessageType.AVIATION_ROUTE });
	 * downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[] {
	 * MessageType.SYNCH_TIME_TYPE, MessageType.OFFLINE_LOGIN,
	 * MessageType.PROVINCE_TYPE, MessageType.NEXT_SITE_CODE }); } else {
	 * downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[] {
	 * MessageType.SYNCH_TIME_TYPE }); } startService(downIntent); }
	 */
    @Override
    public void onBackPressed() {

        // super.onBackPressed();
    }

    private void showExit() {
        final BaseDialog dialog = new BaseDialog(this);
        dialog.setTitles(this.getText(R.string.exit_notice).toString());
        dialog.show();
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
                if (res) {
                    StoApplication.getStoJni()
                            .Enable_touch_screen();
                    stopAllServiceExit();
                }

            }
        });
    }

    private void stopAllServiceExit() {
        stopService((new Intent(this, TimingService.class)));
        stopService(new Intent(this, UploadDataService.class));
        stopService(new Intent(this, StoDownServer.class));

        // 状态栏下拉
        StoApplication.getStoJni().TurnOnStatusBarExpand();
        // 触摸屏解锁
        StoApplication.getStoJni().TurnOnScreenLock();

        this.finish();
    }

    private void startDown() {
        Intent downIntent = new Intent(this, StoDownServer.class);

        downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS, new int[]{
                MessageType.NEXT_SITE_CODE, MessageType.SITE_CODE_FULL,
                MessageType.PROVINCE_TYPE, MessageType.AVIATION_ROUTE,
                MessageType.PROBLEM_TYPE, MessageType.ORDER_REASON_TYPE,
                MessageType.SITE_SALEAS_TYPE, MessageType.USER_INFO_TABLE,
                MessageType.USER_RULE_TABLE, MessageType.ORG_RULE_TABLE,
                MessageType.DATADICT_TABLE, MessageType.GOODS_TYPE_TABLE,
                MessageType.EFFECTIVE_TYPE_TABLE, MessageType.FREQUENCY_TABLE,
                MessageType.SCAN_RULE_TABLE});

        startService(downIntent);
    }

    private void testLogin() {
        UnifiedStaticType.loginType = BaseMessage.SALES_VERSION;
        allStartService();
        // testDown();
        Intent intent = new Intent(this, StoSalesMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

        //    intoMenu(StoSitePointSelectActivity.class, false);
    }

    private void startActAndStartAlarm(Intent intent) {
        AlarmClockManager.getInstance(this).startAutoUploadAlarm(
                StoFilePreference.getInstance(this).getAutoUploadTime());
        AlarmClockManager.getInstance(this).start24Alarm();
        startActivity(intent);
    }

    /**
     * Add by wangjie 设置Jpush标签回调接口
     */
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.e("sto", logs);
                    Toast.makeText(StoLoginActivity.this,"设置极光服务分组成功...",Toast.LENGTH_SHORT).show();
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.e("sto", logs);
                    if (JPushUtil.isConnected(getApplicationContext())) {
                        handler.sendMessageDelayed(handler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Log.e("sto", "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("sto", logs);
            }

        }

    };
}
